const loading = $("loading");
const invalid = $("invalid");
const error = $("error");

function $(id) { 
  return document.getElementById(id);
}

function show(id) { 
  $(id).style.display = "block";
}

function hide(id) { 
  $(id).style.display = "none";
}

var contentURL;
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { 
  const activeTab = tabs[0];
  contentURL = activeTab.url;

  // 网址是否匹配可以截取图片
  if (isUrlMatches(contentURL)) {
    let loaded = false;
    // 需要滚动网页内容,这里以编程的方式直接运行content.js文件
    chrome.scripting.executeScript(
      {
        target: { tabId: activeTab.id },
        files: ['content.js']
      },
      function () {
        // todos
        loaded = true;
        show("loading");
        // 通过消息传递通知content.js
        chrome.tabs.sendMessage(
          activeTab.id,
          { msg: "scrollPage" },
          function () { 
            console.log("发送消息之后....")
          }
        )
      }
    );

    window.setTimeout(() => {
      if (!loaded) {
        show("error")
      }
    }, 1000);
  }
  else { 
    // 网址不匹配
    show("invalid");
  }
})

const matches = ["http://*/*", "https://*/*", "file://*/*", "ftp://*/*"];
const noMatches = [/^https?:\/\/www.baidu.com\/.*$/]

function isUrlMatches(url) { 
  for (let i = 0; i<noMatches.length; i++) { 
    if (noMatches[i].test(url)) { 
      return false;
    }
  }

  let r;
  for (let i = 0; i < matches.length; i++) { 
    r = new RegExp("^" + matches[i].replace(/\*/g, ".*") + "$");
    if (r.test(url)) { 
      return true;
    }
  }

  return false;
}